"""
让聊天带有记忆
0.构建大模型
1.创建带历史消息得占位符的提示词模板 ChatPromptTemplate.from_messages
2.创建普通的链
3.创建取session_history方法，key=session_id
4.创建带有记忆可运行的链
from langchain_core.runnables import RunnableWithMessageHistory
RunnableWithMessageHistory(
    普通链，
    取session_history方法(自定义)，
    提示词模板用户输入变量名,
    提示词模板历史消息占位符变量名)
5.记忆可运行的链invoke调用，
invoke参数 为json即字典 如 {"content":"xxx"},config={"configurable":{"session_id":1}}

重要类
1.聊天消息历史类  from langchain_community.chat_message_histories import RedisChatMessageHistory
2.带记忆消息可运行类  from langchain_core.runnables import RunnableWithMessageHistory

注意：session_id 类型为str
"""
from model_utils import getLLM
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.output_parsers import StrOutputParser
from langchain_community.chat_message_histories import RedisChatMessageHistory
from langchain_core.runnables import RunnableWithMessageHistory

llm = getLLM()

template = ChatPromptTemplate.from_messages([
    ("system","请用中文回答"),
    MessagesPlaceholder(variable_name="history"),
    ("human","{question}")
])

parser = StrOutputParser()

chain = template | llm | parser

#读取session_id的用户历史对话记录

store = {}

def get_by_session_id(session_id):
    return RedisChatMessageHistory(session_id=session_id,url="redis://localhost:6380/0")


run_with_chain = RunnableWithMessageHistory(chain,
                                            get_by_session_id,
                                            input_messages_key="question",
                                            history_messages_key="history")


config = {"configurable":{"session_id":"id12345"}}

r = run_with_chain.invoke({"question":"我叫张三"},config=config)
print(r)
print(store)
print("----------------")
r = run_with_chain.invoke({"question":"我叫什么名字"},config=config)
print(r)